package com.liu.system.manage.util;

import com.liu.system.manage.domain.DMenu;
import com.liu.system.manage.domain.TreeNode;



import java.util.ArrayList;
import java.util.List;

public class MenuTreeUtil {

    /**
     * 两层循环实现建树
     * @param treeNodes 传入的树节点列表
     * @return
     */
    public static List<TreeNode> bulid(List<DMenu> treeNodes) {

        List<TreeNode> trees = new ArrayList<TreeNode>();

        for (TreeNode node : treeNodes) {

            if ("0".equals(node.getParentId())) {
                trees.add(node);
            }

            for (TreeNode it : treeNodes) {
                if (it.getParentId().equals(node.getId()) ) {
                    if (node.getChildren() == null) {
                        node.setChildren(new ArrayList<TreeNode>());
                    }
                    node.getChildren().add(it);
                }
            }
        }
        return trees;
    }


    /**
     * 使用递归方法建树
     * @param treeNodes
     * @return
     */
    public static List<TreeNode> buildByRecursive(List<TreeNode> treeNodes) {
        List<TreeNode> trees = new ArrayList<TreeNode>();
        for (TreeNode node : treeNodes) {
            if ("0".equals(node.getParentId())) {
                trees.add(findChildren(node,treeNodes));
            }
        }
        return trees;
    }


    /**
     * 递归查找子节点
     * @param treeNodes
     * @return
     */
    public static TreeNode findChildren(TreeNode treeNode,List<TreeNode> treeNodes) {
        treeNode.setChildren(new ArrayList<TreeNode>());

        for (TreeNode node : treeNodes) {
            if(treeNode.getId().equals(node.getParentId())) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<TreeNode>());
                }
                treeNode.getChildren().add(findChildren(node,treeNodes));
            }
        }
        return treeNode;
    }



}
